﻿namespace WebMarkupMin.Web.Helpers
{
	using System.Collections.Generic;
	using System.Text.RegularExpressions;

	using Constants;

	/// <summary>
	/// Content type helper
	/// </summary>
	public static class ContentTypeHelper
	{
		/// <summary>
		/// XML-based content type list
		/// </summary>
		private static readonly ISet<string> _xmlBasedContentTypes = new HashSet<string>
		{
			ContentType.Xml, ContentType.DeprecatedXml, ContentType.Dtd, ContentType.Xslt,
			ContentType.Rss, ContentType.Atom, ContentType.RdfXml,
			ContentType.Soap, ContentType.Wsdl,
			ContentType.Svg, ContentType.MathMl, ContentType.VoiceXml, ContentType.Srgs
		};

		private const string NAME_PATTERN = @"[\w-.:+]+";

		/// <summary>
		/// Text-based content type regular expression
		/// </summary>
		private static readonly Regex _textBasedContentTypePrefixRegex = new Regex(
			string.Format(@"^text/{0}|application/(xml(\-{0})?|{0}\+xml|{0}script|json)$", NAME_PATTERN)
		);


		/// <summary>
		/// Checks whether the content type is based on XML
		/// </summary>
		/// <param name="contentType">Content type</param>
		/// <returns>Result of check (true - based on XML; false - not based on XML)</returns>
		public static bool IsXmlBasedContentType(string contentType)
		{
			string contentTypeInLowercase = contentType.ToLowerInvariant();

			return _xmlBasedContentTypes.Contains(contentTypeInLowercase);
		}

		/// <summary>
		/// Checks whether the content type is based on text
		/// </summary>
		/// <param name="contentType">Content type</param>
		/// <returns>Result of check (true - based on text; false - not based on text)</returns>
		public static bool IsTextBasedContentType(string contentType)
		{
			string contentTypeInLowercase = contentType.ToLowerInvariant();

			return _textBasedContentTypePrefixRegex.IsMatch(contentTypeInLowercase);
		}
	}
}